package cn.micro.eye.commons.validate.validator;

import cn.micro.eye.commons.validate.NotInEnum;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;

/**
 * The Not In Enum Constraint Validator
 *
 * @author lry
 */
@Slf4j
public class NotInEnumValidator implements ConstraintValidator<NotInEnum, Integer> {

    private Class<?>[] cls;
    private NotInEnum notInEnum;

    @Override
    public void initialize(NotInEnum notInEnum) {
        this.cls = notInEnum.target();
        this.notInEnum = notInEnum;
        if (cls.length == 0) {
            throw new IllegalArgumentException("The @NotInEnum target is null");
        }
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if (value == null) {
            return false;
        }

        for (Class<?> cl : cls) {
            try {
                if (cl.isEnum()) {
                    Object[] objArray = cl.getEnumConstants();
                    Method method = cl.getMethod(notInEnum.val());
                    for (Object obj : objArray) {
                        Object code = method.invoke(obj);
                        if (value.equals(code)) {
                            return true;
                        }
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }

        return false;
    }

}